<template>
  <div style="overflow: hidden; width: 100%; height: 100%">
    <VxeBasicTable ref="tableRef" v-bind="gridOptions">
      <template #action="{ row }">
        <TableAction outside :actions="createActions(row)" />
      </template>

      <template #isReturn_default="{ row }">
        <div style="cursor: pointer">
          <div v-if="!row.isReturn">否</div>
          <div v-if="row.isReturn == 1" style="color: green" @click="openOrderModal(row)"
            >是(点击查看符合单据)</div
          >
        </div>
      </template>
    </VxeBasicTable>

    <FormModal @register="register" @success="handleSuccess" />
    <OrderListModal @register="orderModal[0]" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';

  import { ref, onMounted, reactive } from 'vue';
  import { useRoute } from 'vue-router';
  import { purchaseOrderTableListApi, priceTableListApi } from '@/api/sys/msUser';
  const route = useRoute();
  import OrderListModal from '../priceList/OrderListModal.vue';

  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema, vxeTableColumns, vxeTableFormSchema } from './role.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';

  import {
    BasicTableProps,
    VxeBasicTable,
    VxeGridInstance,
    VxeGridListeners,
  } from '@/components/VxeTable';

  defineOptions({ name: 'userNoteList' });
  const { createMessage } = useMessage();
  const loading = ref(false);

  const userName = ref(route.params?.userName);

  const [register, { openModal, closeModal }] = useModal();
  const orderModal = useModal();

  const tableRef = ref<VxeGridInstance>();

  const gridOptions = reactive<BasicTableProps>({
    id: 'VxeTable',
    // keepSource: true,
    editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
    showOverflow: true,
    size: 'mini',
    height: 'auto',
    columns: vxeTableColumns,
    toolbarConfig: {
      buttons: [
        // {
        //   content: '新增',
        //   buttonRender: {
        //     name: 'AButton',
        //     props: {
        //       type: 'primary',
        //       preIcon: 'mdi:page-next-outline',
        //     },
        //     events: {
        //       click: () => {
        //         // tableRef.value?.insert({ name: '新增的' });
        //         // createMessage.success('新增成功');
        //         handleCreate();
        //       },
        //     },
        //   },
        // },
      ],
    },
    formConfig: {
      enabled: true,
      items: vxeTableFormSchema,
    },
    pagerConfig: {
      pageSize: 20,
    },
    proxyConfig: {
      props: {
        result: 'data.list',
        list: 'data.list',
        total: 'data.totalResult',
        message: 'message',
      },
      ajax: {
        query: async ({ page, form }) => {
          return priceTableListApi({
            page: page.currentPage,
            pageSize: page.pageSize,
            IfXuNiJian: 1,
            ...form,
          });
        },
        // queryAll: async ({ form }) => {
        //   return await demoListApi(form);
        // },
      },
    },
  });

  // 操作按钮（权限控制）
  const createActions = (record) => {
    const actions: ActionItem[] = [
      {
        label: '详情',
        onClick: () => {
          console.log(record);
        },
      },
      // {
      //   label: '编辑',
      //   onClick: () => {},
      // },
      // {
      //   label: '删除',
      //   color: 'error',
      //   popConfirm: {
      //     title: '是否确认删除',
      //     confirm: () => {
      //       tableRef.value?.remove(record);
      //     },
      //   },
      // },
    ];

    return actions;
  };

  const gridEvents: VxeGridListeners = {
    formSubmit() {
      console.log('form submit');
    },
    formReset() {
      console.log('form reset');
    },
    pageChange({ pageSize, currentPage }) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
      // handlePageData()
    },
  };

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function format(seconds) {
    //秒转化为分钟格式
    let s = Math.trunc(seconds);
    let minInt = Math.floor(s / 60);
    let min = minInt >= 10 ? minInt : '00' + minInt;
    s -= 60 * min;
    let sec = s >= 10 ? s : '00' + s;
    return min + ':' + sec;
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }
  function handleView(record: Recordable) {
    let url = record.mp3Url ? record.mp3Url : record.remoteUrl;
    // let url=record.remoteUrl;
    window.open(url);
  }

  function handleDelete(record: Recordable) {
    //console.log(record);

    deleteApi(record)
      .then((res) => {
        createMessage.success(res.message);
      })
      .catch((res) => {
        createMessage.error(res.message);
      })
      .finally(() => {
        reload();
      });
  }

  function handleSuccess() {
    reload();
  }
  const arrHeader = [
    {
      key: 'userName',
      value: '姓名',
    },
    {
      key: 'levelName',
      value: '职级',
    },
  ];

  function getHeadArr() {
    let arr = [];
    arrHeader.forEach((r) => {
      arr.push(r.value);
    });
    return arr;
  }

  function changeSubmitArr(results) {
    let data = {
      list: [],
    };
    let list = [];
    results.forEach((r) => {
      let json = {};
      for (let key in r) {
        arrHeader.forEach((e) => {
          if (e.value == key) {
            json[e.key] = r[key];
          }
        });
      }
      data.list.push(json);
    });
    return data;
  }

  function openOrderModal(record: Recordable) {
    orderModal[1].openModal(true, record);
  }
</script>
